package org.jeecg.modules.gis.util;

import dm.jdbc.driver.DmdbConnection;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

/**
 * GisDbUtil：从当前 DataSource 获取数据库类型（不依赖 DynamicRoutingDataSource）
 */
@Component
public class GisDbUtil {

    private final DataSource dataSource;

    public GisDbUtil(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取当前数据源的数据库类型（小写）
     * @return 比如 postgresql、dm、oracle、mysql、sqlserver
     */
    public String getDbType() {
        try (Connection conn = dataSource.getConnection()) {
            DatabaseMetaData metaData = conn.getMetaData();
            String productName = metaData.getDatabaseProductName();
            return normalizeDbType(productName);
        } catch (Exception e) {
            throw new RuntimeException("无法获取数据库类型", e);
        }
    }

    private String normalizeDbType(String productName) {
        if (productName == null) return "unknown";
        String name = productName.toLowerCase();
        if (name.contains("postgresql")) return "postgresql";
        if (name.contains("dm")) return "dm";
        if (name.contains("oracle")) return "oracle";
        if (name.contains("mysql")) return "mysql";
        if (name.contains("sql server")) return "sqlserver";
        return "unknown";
    }
    public String formatTableName(String dbType, String tableName) {
        switch(dbType.toLowerCase()) {
            case "mysql":
                return "`" + tableName + "`";
            case "postgresql":
                return "\"" + tableName + "\"";
            case "oracle":
                return tableName.toUpperCase(); // Oracle一般大写无引号
            case "dm":
            case "dameng":
                return "\"" + tableName + "\"";
            default:
                return tableName;
        }
    }

}
